package com.xmall.product.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.define.constants.CommonConstants;
import com.xmall.product.define.dict.AttrOptionTypeEnum;
import com.xmall.product.define.dto.baseAttr.BaseAttrDto;
import com.xmall.product.define.request.attr.BaseAttrQueryParams;
import com.xmall.product.entity.AttrOption;
import com.xmall.product.mapper.AttrOptionMapper;
import com.xmall.product.service.IAttrOptionService;
import com.xmall.product.service.IBaseAttrService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  服务实现类
 */
@Service
public class AttrOptionServiceImpl extends ServiceImpl<AttrOptionMapper, AttrOption> implements IAttrOptionService {

    @Resource
    private IBaseAttrService attrService;

    @Override
    public void save(Long attrId, AttrOptionTypeEnum type, List<String> optionList) {
        if(CollectionUtil.isNotEmpty(optionList)) {
            Integer sort = CommonConstants.DEFAULT_SORT_NUM;

            List<AttrOption> updateAttrOptionList = new ArrayList<>();
            for (String option : optionList) {
                AttrOption attrOption = new AttrOption();
                attrOption.setAttrId(attrId);
                attrOption.setAttrValue(option);
                attrOption.setAttrOptionSn(IdUtil.getSnowflakeNextId());
                attrOption.setSort(sort++);
                attrOption.setType(type.getType());
                updateAttrOptionList.add(attrOption);
            }

            this.saveBatch(updateAttrOptionList);
        }
    }

    @Override
    public void removeByAttrId(Long attrId, AttrOptionTypeEnum type) {
        this.remove(new QueryWrapper<AttrOption>().eq("attr_id", attrId).eq("type", type.getType()));
    }

    @Override
    public void removeByGroupId(Long groupId) {
        List<BaseAttrDto> attrList = attrService.listWithCascade(new BaseAttrQueryParams().setGroupId(groupId));
        List<Long> attrOptionIdList = attrList.stream().map(BaseAttrDto::getOptionList).flatMap(x -> x.stream()).map(AttrOption::getId).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(attrOptionIdList)) {
            this.removeByIds(attrOptionIdList);
        }
    }
}
